package com.wrupple.muba.catalogs.client.widgets.impl;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class TextListEditor extends Composite implements HasValue<List<String>> {

	private class Clicker implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			addTextBox(null);
		}

	}

	private class Finish implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			finish();
		}

	}

	private FlexTable table;
	private List<TextBox> list;

	public TextListEditor() {
		super();
		CatalogUserInterfaceMessages c = GWT.create(CatalogUserInterfaceMessages.class);
		VerticalPanel main = new VerticalPanel();
		FlowPanel bottom = new FlowPanel();
		Button button = new Button(c.addNew(), new Clicker());
		Button end = new Button(c.ok(), new Finish());
		list = new ArrayList<TextBox>();
		table = new FlexTable();
		main.add(table);
		main.add(bottom);
		bottom.add(end);
		bottom.add(button);
		initWidget(main);
	}

	protected void finish() {
		ValueChangeEvent.fire(this, getValue());
	}

	@Override
	public List<String> getValue() {
		List<String> regreso = new ArrayList<String>(list.size());
		String value = null;
		for (TextBox box : list) {
			value = box.getValue().trim();
			if (value.length() == 0) {
				// skip
			} else {
				regreso.add(value);
			}
		}
		return regreso;
	}

	@Override
	public void setValue(List<String> value) {
		list.clear();
		table.removeAllRows();
		if (value != null) {

			for (String s : value) {
				addTextBox(s);
			}
		}
	}

	private void addTextBox(String s) {
		TextBox temp = null;
		int rows = 0;
		temp = new TextBox();
		if (s != null) {
			temp.setValue(s);
		}
		list.add(temp);
		rows = table.getRowCount();
		table.setWidget(rows, 0, temp);

	}

	@Override
	public HandlerRegistration addValueChangeHandler(ValueChangeHandler<List<String>> handler) {
		return addHandler(handler, ValueChangeEvent.getType());
	}

	@Override
	public void setValue(List<String> value, boolean fireEvents) {
		setValue(value);
		if (fireEvents) {
			ValueChangeEvent.fire(this, getValue());
		}
	}

}
